package Controller;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.HashMap;
import static java.nio.file.StandardWatchEventKind.*;
import java.nio.file.attribute.*;

/**
 * @author Rinat
 *
 */
public class OSListnerService implements Executor{
	
	private WatchService watcher;
	private HashMap<WatchKey,Path> keys;
	
	
	public OSListnerService() {
		// TODO Auto-generated constructor stub
		 try {
			 watcher = FileSystems.getDefault().newWatchService();
			 keys = new HashMap<WatchKey,Path>();
		 } catch (IOException e) {}
	}
	

	 public void registerPath(String path)
	 {
	   try {
	    Path dir = Paths.get(path);
	    registerAll(dir);
	    WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
	    keys.put(key, dir);
	  } catch (IOException e) {}
	 }
	 
	/**
	 * Register the given directory, and all its sub-directories, with the
	 * WatchService.
	 */
    private void registerAll(final Path start) throws IOException {
        // register directory and sub-directories
        Files.walkFileTree(start, new SimpleFileVisitor<Path>(){
        	@Override
        	public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
        			throws IOException {
        		// TODO Auto-generated method stub
        		register(dir);
        		return FileVisitResult.CONTINUE;
        	}
        });
    }

    
    public void register(Path dir)
    {
       try{
       WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
       keys.put(key, dir);
     } catch (IOException e) {}
    }
	
	
	public void execute() {
		// TODO Auto-generated method stub
		
	}

}
